﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Localization;
using MvcSample.Data.Core;
using MvcSample.Models;
using MvcSample.Services;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MvcSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly IStringLocalizer<HomeController> _stringLocalizer;
        private readonly IHtmlLocalizer<HomeController> _htmlLocalizer;
        private readonly IStudentService _studentService;
        private readonly IMemoryCache _memoryCache;
        public HomeController(IStringLocalizer<HomeController> stringLocalizer,
            IHtmlLocalizer<HomeController> htmlLocalizer,
            IStudentService studentService,
            IMemoryCache memoryCache)
        {
            _stringLocalizer = stringLocalizer;
            _htmlLocalizer = htmlLocalizer;
            _studentService = studentService;
            _memoryCache = memoryCache;
        }
        // GET: /<controller>/
        [ResponseCache(CacheProfileName = "never")]
        public async Task<IActionResult> Index()
        {
            //throw new Exception();

            ViewData["title"] = _stringLocalizer["title"];
            var key = $"{nameof(HomeController)}_{nameof(Index)}";
            if (!_memoryCache.TryGetValue<List<StudentOutputDto>>(key, out List<StudentOutputDto> students))
            {
                var rt = await _studentService.GetAllAsync();

                var options = new MemoryCacheEntryOptions()
                    .SetSlidingExpiration(TimeSpan.FromSeconds(30))
                    .RegisterPostEvictionCallback(Callback);
                _memoryCache.Set(key, rt);
                return View(rt);
            }
            return View(students);
        }

        private void Callback(object key, object value, EvictionReason reason, object state)
        {
            throw new NotImplementedException();
        }

        public async Task<IActionResult> Detail(int id)
        {
            var rt = await _studentService.GetByIdAsync(id);
            return View(rt);
        }
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public async Task<IActionResult> Create(StudentCreateVm vm)
        {
            var stu = new Student()
            {
                BirthDay = vm.BirthDay,
                FirstName = vm.FirstName,
                Gender = vm.Gender,
                LastName = vm.LastName
            };
            await _studentService.AddAsync(stu);
            return RedirectToAction(nameof(Index));
        }
    }
}
